'''
将a.jpg和 config.py中的标注信息转为xml文件
'''
# coding=utf-8

import argparse
from xml.dom.minidom import Document
import os
import os.path
from PIL import Image

def writeXml(tmp,imgname, w, h, wxml, config):        
    doc = Document()
    #owner
    annotation = doc.createElement('annotation')
    doc.appendChild(annotation)

    filename = doc.createElement('filename')
    annotation.appendChild(filename)
    filename_txt = doc.createTextNode(imgname)
    filename.appendChild(filename_txt)

    #twos#
    size = doc.createElement('size')
    annotation.appendChild(size)
 
    width = doc.createElement('width')
    size.appendChild(width)
    width_txt = doc.createTextNode(str(w))
    width.appendChild(width_txt)
 
    height = doc.createElement('height')
    size.appendChild(height)
    height_txt = doc.createTextNode(str(h))
    height.appendChild(height_txt)
 
    depth = doc.createElement('depth')
    size.appendChild(depth)
    depth_txt = doc.createTextNode("3")
    depth.appendChild(depth_txt)
 
    for i in range(0,len(config.modify_region)):
        # if(config.modify_region[i]['attr'] == 'title' or config.modify_region[i]['attr'] == 'text'):
        #     continue;
        #threes#
        attr = config.modify_region[i]['attr']
        if attr == 'imagegraph' or attr == 'image':
            attr ='figure'
        if attr == 'tableimg' or attr == 'table':
            attr = 'table'
        if attr == 'formula':
            attr = 'equation'
        if attr == 'title' or attr == 'text':
            continue
        object_new = doc.createElement("object")
        annotation.appendChild(object_new)
 
        name = doc.createElement('name')
        object_new.appendChild(name)
        name_txt = doc.createTextNode(attr)
        name.appendChild(name_txt)
    
        difficult = doc.createElement('difficult')
        object_new.appendChild(difficult)
        difficult_txt = doc.createTextNode("0")
        difficult.appendChild(difficult_txt)
        #threes-1#
        bndbox = doc.createElement('bndbox')
        object_new.appendChild(bndbox)
 
        xmin = doc.createElement('xmin')
        bndbox.appendChild(xmin)
        temp = config.modify_region[i]['x']
        if temp < 0:
            temp = 0
        xmin_txt = doc.createTextNode(str(temp))
        xmin.appendChild(xmin_txt)
 
        ymin = doc.createElement('ymin')
        bndbox.appendChild(ymin)
        temp = config.modify_region[i]['y']
        if temp < 0:
            temp = 0
        ymin_txt = doc.createTextNode(str(temp))
        ymin.appendChild(ymin_txt)
 
        xmax = doc.createElement('xmax')
        bndbox.appendChild(xmax)
        temp = config.modify_region[i]['x']+config.modify_region[i]['w']
        if temp > w:
            temp = w -1
        xmax_txt = doc.createTextNode(str(temp))
        xmax.appendChild(xmax_txt)
 
        ymax = doc.createElement('ymax')
        bndbox.appendChild(ymax)
        temp = config.modify_region[i]['y']+config.modify_region[i]['h']
        if temp > h:
            temp = h -1
        ymax_txt = doc.createTextNode(str(temp))
        ymax.appendChild(ymax_txt)
        #threee-1#
        #threee#
    # for i in range(0,len(config.modify_region)):
        
    #     object_new = doc.createElement("object")
    #     annotation.appendChild(object_new)
 
    #     name = doc.createElement('name')
    #     object_new.appendChild(name)
    #     name_txt = doc.createTextNode(config.modify_region[i]['attr'])
    #     name.appendChild(name_txt)
    
    #     difficult = doc.createElement('difficult')
    #     object_new.appendChild(difficult)
    #     difficult_txt = doc.createTextNode("0")
    #     difficult.appendChild(difficult_txt)
    #     #threes-1#
    #     bndbox = doc.createElement('bndbox')
    #     object_new.appendChild(bndbox)
 
    #     xmin = doc.createElement('xmin')
    #     bndbox.appendChild(xmin)
    #     xmin_txt = doc.createTextNode(str(config.modify_region[i]['x']))
    #     xmin.appendChild(xmin_txt)
 
    #     ymin = doc.createElement('ymin')
    #     bndbox.appendChild(ymin)
    #     ymin_txt = doc.createTextNode(str(config.modify_region[i]['y']))
    #     ymin.appendChild(ymin_txt)
 
    #     xmax = doc.createElement('xmax')
    #     bndbox.appendChild(xmax)
    #     xmax_txt = doc.createTextNode(str(config.modify_region[i]['x']+config.modify_region[i]['w']))
    #     xmax.appendChild(xmax_txt)
 
    #     ymax = doc.createElement('ymax')
    #     bndbox.appendChild(ymax)
    #     ymax_txt = doc.createTextNode(str(config.modify_region[i]['y']+config.modify_region[i]['h']))
    #     ymax.appendChild(ymax_txt)

    tempfile = tmp + "test.xml"
    with open(tempfile, "wb") as f:
        f.write(doc.toprettyxml(indent = '\t', encoding='utf-8'))
 
    rewrite = open(tempfile, "r")
    lines = rewrite.read().split('\n')
    newlines = lines[1:len(lines)-1]
    
    fw = open(wxml, "w")
    for i in range(0, len(newlines)):
        fw.write(newlines[i] + '\n')
    
    fw.close()
    rewrite.close()
    os.remove(tempfile)
    return

def make_xml(xml_path, page_config=None):
    if page_config is not None:
        config = page_config
    else:
        import config
    img_path = config.normal_imageName['jpgPath']
    temp = ".\\temp\\"
    if not os.path.exists(temp):
        os.mkdir(temp)
        (path,file) = os.path.split(img_path)
        print(file + "-->Start to make xml file!")
        im=Image.open(img_path)
        width= int(im.size[0])
        height= int(im.size[1])
        filename = xml_path + os.path.splitext(file)[0] + '.xml'
        print(filename, [width,height])
        writeXml(temp, file, width, height, filename, config)
    os.rmdir(temp)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Make xml!!!")
    parser.add_argument("--xmlPath", default="./synthetic_data/xml/", type=str, help="xml path")
    opt = parser.parse_args()
    xml_path = opt.xmlPath

    if not os.path.exists(xml_path):
        os.mkdir(xml_path)

    make_xml(xml_path)